package com.wujilin.okra.fragment;

import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_ID;
import static com.wujilin.okra.Okra.FORMATTER_DATE_TIME;
import static com.wujilin.okra.Okra.F_CATEGORY_ID;

import org.joda.time.DateTime;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;
import com.wujilin.okra.model.Model;

/**
 * 
 * @author Belin Wu
 */
public class ObjectiveNewFragment extends DialogFragment implements OnClickListener {
	private EditText objectiveContent;
	
	private Callback callback;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		callback = (Callback) activity;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_objective, null);
		objectiveContent = (EditText) view.findViewById(R.id.objective_content);
		
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.new_objective)
				.setView(view)
				.setPositiveButton(android.R.string.ok, this)
				.setNegativeButton(android.R.string.cancel, this)
			.create();
		return dialog;
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == BUTTON_POSITIVE) {
			Model model = new Model();
			
			String content = objectiveContent.getText().toString();
			model.set("content", content);
			DateTime now = DateTime.now();
			int year = now.getYear();
			int month = now.getMonthOfYear();
			int quarter = month / 3 + (month % 3 == 0 ? 0 : 1);
			model.set("year", year);
			model.set("quarter", quarter);
			model.set("time", now.toString(FORMATTER_DATE_TIME));
			
			Bundle args = getArguments();
			if (args != null && args.containsKey(EXTRA_CATEGORY_ID)) {
				model.set(F_CATEGORY_ID, args.getLong(EXTRA_CATEGORY_ID));
			}
			
			long id = Sql.insert("objective", model);
			if (id != -1) {
				callback.onOkraSelected(id);
			}
		}
	}
	
	/**
	 * The callbacks that the hosting activity must implement.
	 * 
	 * @author Belin Wu
	 *
	 */
	public static interface Callback {
		/**
		 * Tell the hosting activity the new objective is been created.
		 * 
		 * @param id The new id of the created objective.
		 */
		void onOkraSelected(long id);
	}
}
